//
//  SDChatConversation.swift
//  SIMChat
//
//  Created by sagesse on 10/4/15.
//  Copyright © 2015 Sagesse. All rights reserved.
//

import UIKit

class SDChatConversation: SIMChatConversation{
    
    var allLoaded = false
}

extension SDChatConversation{
    override func queryMessages(total: Int, last: SIMChatMessage?, _ finish: ([SIMChatMessage] -> Void)?, _ fail: SIMChatFailBlock?) {
        super.queryMessages(total, last: last, { [weak self] ms in
            // 己经完成了
            guard ms.count < total && !(self?.allLoaded ?? true) else {
                finish?(ms)
                return
            }
            SIMLog.trace("finish")
            // 并没有
            finish?(ms)
        }, fail)
    }
    
    
    override func sendMessage(m: SIMChatMessage, isResend: Bool, _ finish: SIMChatFinishBlock?, _ fail: SIMChatFailBlock?) {
        super.sendMessage(m, isResend: isResend, {
            // 1秒后完成
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)), dispatch_get_main_queue()) {
                SIMLog.trace("finish")
                print("********type***********")
                print(m.type)
                print("********type***********")
                
                if(m.type == 1){
                    
                    // 检查
                    guard let content = m.content as? SIMChatMessageContentText else {
                        return
                    }
                    
                    let text = content.text!
                    print(text)
                    let foldName = m.sender!.identifier+"&"+m.receiver!.identifier+"/"

                    let filePath = NSUUID().UUIDString + "$" + m.sender!.identifier+".txt"
                    
                    let isOk = Common.createFile(foldName,filePath: filePath, fileContent: text)
                    if(isOk){
                        print("保存发送文本成功:"+filePath)
                    }else{
                        print("保存发送文本失败!")
                    }
                    
                    Common.sendMessageToText(content.text!) { (isOk) -> Void in
                    if(isOk == true){
                        m.status = .Sent
                        m.statusChanged()
                        
                        finish?()
                        print("发送成功!")
                    }else{
                        m.status = .Error
                        m.statusChanged()
                        
                        finish?()
                        print("发送失败!")
                    }
                    }
                    
                }else if(m.type == 2){
                    
                    // 检查
                    guard let content = m.content as? SIMChatMessageContentImage else {
                        return
                    }
                    print("********picture***********")
                    print(content.originSize.width)
                    print(content.originSize.height)
                    print(m.sender?.identifier)
                    print(m.receiver?.identifier)
                    print("********picture***********")
                    
                    let foldPath = m.sender!.identifier+"&"+m.receiver!.identifier+"/"
                    
                    let pathName = NSUUID().UUIDString + "@" + (m.sender?.identifier)! + "$" + (m.receiver?.identifier)! + ".png"
                    
                    UIPasteboard.generalPasteboard().image = *(content.origin)
                    let path = self.getImagePath((*(content.origin))!, newSize: content.originSize, percent: 1,foldPath: foldPath, imageName: pathName)
                
                    print("********path***********")
                    print(path)
                    print("********path***********")
                    // 生成连接(这可以降低内存使用)
                    let urlPicture = NSURL(fileURLWithPath: path)
                    
                    print("******************")
                    print(urlPicture)
                    print("******************")
                    
                    let cc = path.characters.split {$0 == "@"}.map(String.init)
                    print(cc[0])
                    print(cc[1])
                    let cs = cc[1].characters.split {$0 == "$"}.map(String.init)
                    print(cs[0])
                    let ccs = cc[0]+"$"+cs[0]+".png"
                    print(ccs)
                    
                    Common.sendMessageToFile(urlPicture) { (isOk) -> Void in
                        if(isOk == true){
                            
                            let isOk = Common.moveFile(path, fileAfter: ccs)
                            
                            if(isOk){
                                print("移动文件成功:"+ccs)
                            }else{
                                print("移动文件失败!")
                            }
                            
                            
                            m.status = .Sent
                            m.statusChanged()
                            
                            finish?()
                            print("发送成功!")
                        }else{
                            m.status = .Error
                            m.statusChanged()
                            
                            finish?()
                            print("发送失败!")
                        }
                    }

                }else if(m.type == 3){
                    // 检查
                    guard let content = m.content as? SIMChatMessageContentAudio else {
                        return
                    }
                    print("********audio***********")
                    let url = String.init(content.url.get()!!)
                    print(url)
                    print("********audio***********")
                    
                    let ul = (url as NSString).substringFromIndex(7)
                    print(ul)
                    let cc = ul.characters.split {$0 == "@"}.map(String.init)
                    print(cc[0])
                    print(cc[1])
                    let cs = cc[1].characters.split {$0 == "$"}.map(String.init)
                    print(cs[0])
                    let ccs = cc[0]+"$"+cs[0]+".acc"
                    print(ccs)
                    
                    Common.sendMessageToFile((content.url.get())!!) { (isOk) -> Void in
                        if(isOk == true){
                            
                            let isOk = Common.moveFile(ul, fileAfter: ccs)
                            
                            if(isOk){
                               print("移动文件成功:"+ccs)
                            }else{
                                print("移动文件失败!")
                            }
                            
                            m.status = .Sent
                            m.statusChanged()
                            
                            finish?()
                            print("发送成功!")
                        }else{
                            m.status = .Error
                            m.statusChanged()
                            
                            finish?()
                            print("发送失败!")
                        }
                    }
                }else{
                    print("未知数据类型请求")
                }
            }

        }, fail)
    }
    
    
    //保存图片到沙箱
    func getImagePath(currentImage: UIImage, newSize: CGSize, percent: CGFloat,foldPath:String, imageName: String)->String{
        //压缩图片尺寸
        UIGraphicsBeginImageContext(newSize)
        currentImage.drawInRect(CGRectMake(0, 0,newSize.width,newSize.height))
        let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        //高保真压缩图片质量
        //UIImageJPEGRepresentation此方法可将图片压缩，但是图片质量基本不变，第二个参数即图片质量参数。
        let imageData:NSData = UIImageJPEGRepresentation(newImage, percent)!
        
        let ci = Common.getFoldName(foldPath) + imageName
        
        print("完整图片路径:"+ci)
        
        //将图片写入文件
        imageData.writeToFile(ci, atomically: false)
        return ci
    }
}
